<template>
  <div class="index">

    <el-row :gutter="20" style="margin-top:10px;" v-if="user">
      <el-col :span="8">
        <div class="grid-content bg-purple">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>个人中心</span>
            </div>

            <div class="personal-relation">
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="uploadFile"
              >
                <img v-if="user.headImage" :src="user.headImage" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <div class="personal-relation">
              <div class="relation-item">ID:
                <div style="float: right; padding-right:20px;">
                  <el-tag type="danger">{{user.id}}</el-tag>
                </div>
              </div>
            </div>
            <div class="personal-relation">
              <div class="relation-item">用户名:
                <div style="float: right; padding-right:20px;">
                  <el-tag type="danger">{{user.username}}</el-tag>
                </div>
              </div>
            </div>
            <div class="personal-relation">
              <div class="relation-item">角色:
                <div style="float: right; padding-right:20px;">
                  <el-tag type="danger">{{roles[0]}}</el-tag>
                </div>
              </div>
            </div>
            <div class="personal-relation">
              <div class="relation-item">真实姓名:
                <div style="float: right; padding-right:20px;">
                  <el-tag type="success">{{user.realName}}</el-tag>
                </div>
              </div>
            </div>
            <div class="personal-relation">
              <div class="relation-item">昵称:
                <div style="float: right; padding-right:20px;">
                  <el-tag type="success">{{user.nickname}}</el-tag>
                </div>
              </div>
            </div>
            <div class="personal-relation">
              <div class="relation-item">手机号:
                <div style="float: right; padding-right:20px;">
                  <el-tag type="success">{{user.phone}}</el-tag>
                </div>
              </div>
            </div>
            <div class="personal-relation">
              <div class="relation-item">邮箱:
                <div style="float: right; padding-right:20px;">
                  <el-tag type="success">{{user.email}}</el-tag>
                </div>
              </div>
            </div>
            <div class="personal-relation">
              <div class="relation-item">QQ:
                <div style="float: right; padding-right:20px;">
                  <el-tag type="success">{{user.qq}}</el-tag>
                </div>
              </div>
            </div>
            <div class="personal-relation">
              <div class="relation-item">注册时间:
                <div style="float: right; padding-right:20px;">
                  <el-tag type="primary">
                    <li class="el-icon-time"></li>
                    {{user.createTime.toString().replace('T',' ')}}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="grid-content bg-purple">


          <!--          简介-->
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>简介</span>
            </div>
            <div style="padding-right:20px;">
              <el-input
                type="textarea"
                :rows="3"
                placeholder="暂无"
                readonly
                v-model="user.intro == null? '暂无':user.intro">
              </el-input>
            </div>
          </el-card>


          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>修改信息</span>
            </div>
            <div>
              <el-form label-width="80px" v-model="userInfo" size="small" label-position="right">
                <el-form-item label="真实姓名" prop="realName">
                  <el-input auto-complete="off" v-model="userInfo.realName" :disabled="isDisable"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="nickname">
                  <el-input auto-complete="off" v-model="userInfo.nickname" :disabled="isDisable"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input auto-complete="off" v-model="userInfo.phone" :disabled="isDisable"></el-input>
                </el-form-item>

                <el-form-item label="性別" prop="sex">
                  <el-switch
                    v-model="userInfo.sex"
                    active-text="男"
                    inactive-text="女"
                    active-value="1"
                    inactive-color="#13ce66"
                    inactive-value="2"
                    :disabled="isDisable"
                  >
                  </el-switch>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input maxlength="18" v-model="userInfo.email" :disabled="isDisable"></el-input>
                </el-form-item>
                <el-form-item label="QQ" prop="qq">
                  <el-input maxlength="18" v-model="userInfo.qq" :disabled="isDisable"></el-input>
                </el-form-item>
                <el-form-item label="简介" prop="intro">
                  <el-input type="textarea" :rows="3" maxlength="18" v-model="userInfo.intro" :disabled="isDisable"></el-input>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button  type="primary" size="small" icon="el-icon-check"   @click="updateUser()" :disabled="isDisable">提交</el-button>
                <el-button  type="success" size="small" icon="el-icon-edit" @click="isDisable= ! isDisable" :disabled="!isDisable">编辑</el-button>
                <el-button  type="danger" size="small" icon="el-icon-close" @click="isDisable = true">禁用</el-button>
                <el-button  type="danger" size="small" icon="el-icon-setting" @click="openModifyPasswordDialog">修改密码</el-button>
              </div>
            </div>
          </el-card>

        </div>
      </el-col>

    </el-row>



    <el-dialog
      title="修改密码"
      :visible.sync="modifyPasswordDialog"
      width="30%"
      center>
      <el-form label-width="100px" v-model="userInfo" size="small" label-position="right">
        <el-form-item label="旧密码">
          <el-input type="password" auto-complete="off" v-model="oldPassword" ></el-input>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input type="password" auto-complete="off" v-model="newPassword" ></el-input>
        </el-form-item>
        <el-form-item label="重复新密码" >
          <el-input type="password" auto-complete="off" v-model="repeatNewPassword" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button  size="small"  @click="modifyPasswordDialog = false">取 消</el-button>
    <el-button type="danger" size="small"  icon="el-icon-setting"  @click="updateUserPasswordByUserName">确定修改</el-button>
  </span>
    </el-dialog>

  </div>

</template>

<script>
  import { mapGetters } from 'vuex'
  import { updateUserById, updateUserHeadImage } from '@/api/user'
  import { uploadFile } from '@/api/qiniu'
  import { updateUserPasswordByUserName } from '../../api/user'

  export default {
    name: 'index',
    inject: ['reload'],
    data() {
      return {
        userInfo: JSON.parse(JSON.stringify(this.$store.getters.user)),
        isDisable: true,
        modifyPasswordDialog:false,
        oldPassword: '',
        newPassword: '',
        repeatNewPassword: ''
      }
    },
    computed: {
      ...mapGetters([
        'user',
        'roles'
      ])
    },
    mounted: function() {
    },
    methods: {
      /**
       * 更新用户
       */
      updateUser() {

        const user = {
          username: this.userInfo.username,
          nickname: this.userInfo.nickname,
          phone: this.userInfo.phone,
          sex: this.userInfo.sex,
          realName: this.userInfo.realName,
          qq: this.userInfo.qq,
          email: this.userInfo.email,
          intro: this.userInfo.intro

        }

        // api获取
        updateUserById(this.userInfo.id, user).then(response => {

          if (response.code == 200) {

            this.$message({
              showClose: true,
              message: response.message,
              type: 'success',
              center: true
            })

            this.$store.dispatch('user/setUser', this.userInfo)
            this.isDisable = true
          }

        }).catch(error => {
          console.log(error)
        })

      },

      /**
       * 上传文件之前
       * @param file
       * @returns {boolean|boolean}
       */
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
          return false
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
          return false
        }

        return isJPG && isLt2M
      },

      /**
       * 上传文件
       * @param fileObj
       */
      uploadFile(fileObj) {

        let formData = new FormData()
        formData.set('file', fileObj.file)

        // api获取
        uploadFile(formData).then(response => {

          if (response.code == 200) {
            const { data } = response

            // 调用更新头像
            this.updateUserHeadImage(data)

          }

        }).catch(error => {
          console.log(error)
        })

      },

      /**
       * 更新头像
       * @param fileObj
       */
      updateUserHeadImage(imageUrl) {

        // api获取
        updateUserHeadImage(this.userInfo.username, imageUrl).then(response => {

          // 数据库更新成功
          if (response.code == 200) {

            this.userInfo.headImage = imageUrl
            this.$store.dispatch('user/setUser', this.userInfo)
          }

        }).catch(error => {
          console.log(error)
        })

      },

      /**
       * 打开修改密码对话框
       */
      openModifyPasswordDialog(){
        this.oldPassword = ''
        this.newPassword = ''
        this.repeatNewPassword = ''
        this.modifyPasswordDialog = true
      },

      /**
       * 更新用户密码
       */
      updateUserPasswordByUserName() {

        if (this.oldPassword == ''
          || this.newPassword == ''
          || this.repeatNewPassword == ''){
          this.$message({
            showClose: true,
            message: '输入不能为空',
            type: 'error',
            center: true
          })
          return
        }

        if (this.newPassword != this.repeatNewPassword
        ){
          this.$message({
            showClose: true,
            message: '新密码输入密码不一致',
            type: 'error',
            center: true
          })
          return
        }

        // api获取
        updateUserPasswordByUserName(this.userInfo.username, this.oldPassword,this.newPassword).then(response => {

          if (response.code == 200) {

            this.$message({
              showClose: true,
              message: response.message,
              type: 'success',
              center: true
            })

            this.modifyPasswordDialog = false
            this.logout()
          }

        }).catch(error => {
          console.log(error)
        })

      },


      async logout() {
        await this.$store.dispatch('user/logout')
        this.$router.push(`/login?redirect=${this.$route.fullPath}`)
      }

    }
  }
</script>

<style lang="scss" scoped>
  //卡片样式
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 100%;
  }

  //文本样式区
  .name-role {
    font-size: 16px;
    padding: 5px;
    text-align: center;
  }

  .sender {
    text-align: center;
    margin: 10px;
  }

  .registe-info {
    text-align: center;
    padding-top: 10px;
  }

  .personal-relation {
    font-size: 16px;
    padding: 0px 5px 15px;
    margin-right: 1px;
    width: 100%
  }

  .relation-item {
    padding: 12px;

  }

  .dialog-footer {
    padding-top: 10px;
    padding-left: 10%;
  }

  //布局样式区
  .el-row {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .el-col {
    border-radius: 4px;
  }

  .bg-purple-dark {
    background: #99a9bf;
  }

  .bg-purple {
    background: #d3dce6;
  }

  .bg-purple-light {
    background: #e5e9f2;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }

  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }

  .avatar-uploader {
    text-align: center;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
    border-radius: 25px;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
  }

  .avatar {
    width: 100px;
    height: 100px;
    border-radius: 25px;
    display: block;
  }
</style>
